<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="语言种类" prop="language">
        <el-select v-model="queryParams.language" placeholder="请选择语言种类" clearable size="small">
          <el-option
            v-for="dict in languageOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
		  plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['reveal:product:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productList"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >

      <el-table-column label="编号" align="center" prop="编号" />
      <!-- <el-table-column label="产品列表图" align="center" prop="id" >
        <template slot-scope="scope">
            <el-image v-if="scope.row.listPic"
            style="width: 50px; height: 50px"
            :src="scope.row.listPic"
            :preview-src-list="[scope.row.listPic]">
          </el-image>
        </template>
      </el-table-column> -->
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品分类  " align="center" prop="typeName" />
      <el-table-column label="语言类型" align="center" prop="language" :formatter="languageFormat" />
      <!-- <el-table-column label="详情图" align="center" prop="img" >
        <template slot-scope="scope">
          <el-image v-if="scope.row.img"
            style="width: 50px; height: 50px"
            :src="scope.row.img.split(',')[0]"
            :preview-src-list="scope.row.img.split(',')">
          </el-image>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="createdDate" width="180"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['reveal:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['reveal:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改产品展示对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">

        <el-form-item  label="产品名称" prop="productName">
          <el-input :style="{width: '40%'}" v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>

        <el-form-item v-if="form.parentId!=0" label="父级产品" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父级产品">
            <el-option
              v-for="product in productParentList"
              :key="product.id"
              :label="product.productName"
              :value="parseInt(product.id)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="产品列表图">
          <uploadImage v-model="form.listPic"/>
        </el-form-item>

        <el-form-item label="产品分类  " prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择产品分类">
            <el-option
              v-for="type in typeList"
              :key="type.id"
              :label="type.typeName"
              :value="parseInt(type.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="语言类型" prop="language">
          <el-select v-model="form.language" placeholder="请选择语言类型">
            <el-option
              v-for="dict in languageOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详情图">
          <el-upload
            :action="uploadImgUrl"
            :http-request="uploadAvatar"
            :headers="headers"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
          <!-- <uploadImage v-model="form.img"/> -->
        </el-form-item>

        <el-form-item label="产品内容" prop="content">
          <el-input  rows='10' v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, exportProduct } from "@/api/reveal/product";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UploadImage from '@/components/UploadImage';
import { listProductType } from "@/api/reveal/productType";
import { getToken } from "@/utils/auth";

import request from '@/utils/request';
export default {
  name: "Product",
  components: {
    UploadImage,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 产品展示表格数据
      productList: [],
      // 产品展示树选项
      productOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 语言类型字典
      languageOptions: [],
      // 查询参数
      queryParams: {
        productName: null,
        parentId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      typeList:[],
      productParentList:[],
      dialogImageUrl: '',
      dialogVisible: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API +  "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      picList: []
    };
  },
  created() {
    this.getList();
    this.getDicts("language").then(response => {
      this.languageOptions = response.data;
    });
  },
  methods: {
    uploadAvatar(item) {
      let formdata = new FormData();
      formdata.append('file', item.file);
      let uid = item.file.uid;
      request({
          url: "/common/upload",
          method: 'post',
          data: formdata
        }).then(res => {
          if (res.code === 200) {
            this.picList.push({ key: uid, url: res.url })
          } else {
               console.log("图片上传失败")
          }
      }).catch(err => {
          console.log(err)
      })
    },


    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isPng = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 10

        if (!isJPG && !isPng) {
          this.$message.error('上传图片只能是 JPG或png 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 10MB!')
        }
        return (isJPG || isPng) && isLt2M
      },
      handleRemove(file, fileList) {
        for (const i in this.picList) {
            if (this.picList[i].key === file.key) {
              this.picList.splice(i, 1)
            }
        }
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        console.log(file);
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
    /** 查询产品展示列表 */
    getList() {

    this.queryParams.parentId = null;
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换产品展示数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.productName,
        children: node.children
      };
    },
	/** 查询部门下拉树结构 */
    getTreeselect() {

      this.queryParams.parentId = '0';
      listProduct(this.queryParams).then(response => {
        this.productParentList = response.data;

      });
    },
    // 语言类型字典翻译
    languageFormat(row, column) {
      return this.selectDictLabel(this.languageOptions, row.language);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {

      this.fileList= [];
      this.picList= [];
      this.form = {
        id: null,
        listPic: null,
        productName: null,
        parentId: null,
        content: null,
        typeId: null,
        language: null,
        img: null,
        createdDate: null,

      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {

      this.reset();
    this.getTreeselect();
    //获取分类
    this.getTypeList();
      this.open = true;
      this.title = "添加产品展示";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
    this.getTreeselect();
    //获取分类
    this.getTypeList();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getProduct(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        //图片
        let img =  response.data.img;
        if(img){
          let imgs =[];
          imgs =img.split(',');
          imgs.forEach((item, index) => {
            let url = {key:index,url:item};
            this.fileList.push(url);
            this.picList.push(url);
          })
        }
        this.title = "修改产品展示";
      });
    },
    getTypeList() {
      listProductType().then(response => {
        this.typeList=response.rows;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let img = "";
            console.log(this.picList);
            this.picList.forEach((item, index) => {
              if(index ===0){
                img += item.url;
              }else{
                img += ","+item.url;
              }

            });
            this.form.img = img;
           if (this.form.id != null) {

            updateProduct(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除选择的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProduct(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    }
  }
};
</script>
